package com.example.everying.service.chat.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.everying.mapper.chat.ChatConversationMapper;
import com.example.everying.model.dto.chat.ConversationDto;
import com.example.everying.model.entity.chat.ChatConversationEntity;
import com.example.everying.model.entity.chat.ChatMessagesEntity;
import com.example.everying.model.entity.user.UserEntity;
import com.example.everying.service.chat.ChatConversationService;
import com.example.everying.service.chat.ChatMessagesService;
import com.example.everying.service.user.UserService;
import com.example.everying.utils.CampusException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ChatConversationServiceImpl extends ServiceImpl<ChatConversationMapper, ChatConversationEntity> implements ChatConversationService {

    @Autowired
    private UserService userService;
    @Autowired
    private ChatMessagesService chatMessagesService;

    /**
     * @param userId
     * @param toUserId
     * @return
     */
    @Override
    public ChatConversationEntity getConversation(String userId, String toUserId) {
        log.info("userId:{},toUserId:{}", userId, toUserId);
        if (userId.equals(toUserId)) {
            throw new CampusException("不能与自己聊天", 201);
        }
        UserEntity user = userService.getUserById(userId);
        UserEntity toUser = userService.getUserById(toUserId);
        log.info("user:{},toUser:{}", user, toUser);
        if (user == null || toUser == null) {
            throw new CampusException("用户不存在", 201);
        }
        int compareResult = userId.compareTo(toUserId);
        String sortedUser1 = compareResult < 0 ? userId : toUserId;
        String sortedUser2 = compareResult < 0 ? toUserId : userId;

        ChatConversationEntity entity = baseMapper.selectOne(new LambdaQueryWrapper<ChatConversationEntity>().
                eq(ChatConversationEntity::getUser1Id, sortedUser1).
                eq(ChatConversationEntity::getUser2Id, sortedUser2));
        if (entity == null) {
            entity = new ChatConversationEntity();
            entity.setUser1Id(sortedUser1);
            entity.setUser2Id(sortedUser2);
            baseMapper.insert(entity);
        }
        return entity;
    }

    /**
     * @param conversationId
     * @param id
     */
    @Override
    public void updateLastMessageId(String conversationId, String id, String userId) {
        log.info("conversationId:{},id:{}", conversationId, id);
        ChatConversationEntity entity = baseMapper.selectById(conversationId);
        if (entity.getLastMessageId()!=null && !entity.getLastMessageId().isEmpty()) {
            entity.setLastRecordId(entity.getLastMessageId());
        }
        entity.setLastMessageId(id);

        entity.setUpdateTime(LocalDateTime.now());
        // 更新会话未读数量
        if (entity.getUser1Id().equals(userId)) {
            entity.setUser2UnreadCount(entity.getUser2UnreadCount() + 1);
        } else {
            entity.setUser1UnreadCount(entity.getUser1UnreadCount() + 1);
        }
        // 恢复删除状态
        entity.setUser1IsDeleted(false);
        entity.setUser2IsDeleted(false);

        baseMapper.update(entity, new QueryWrapper<ChatConversationEntity>().eq("id", conversationId));

    }

    //    /**
//     * 获取用户的会话列表（带最后一条消息和未读数）
//     */
//    @Override
//    public List<ConversationDto> getUserConversations(String userId) {
//        // 1. 查询用户参与的所有会话
//        List<ChatConversationEntity> conversations = lambdaQuery()
//                .and(q -> q.eq(ChatConversationEntity::getUser1Id,  userId)
//                        .or()
//                        .eq(ChatConversationEntity::getUser2Id, userId))
//                .orderByDesc(ChatConversationEntity::getUpdateTime)
//                .list();
//
//        // 2. 组装DTO
//        // 确定对方用户信息
//        // 获取最后一条消息
//        // 判断用户是用户1还是用户2
//
//        return conversations.stream().map(conv -> {
//            ConversationDto dto = new ConversationDto();
//            dto.setConversationId(conv.getId());
//
//            // 确定对方用户信息
//            String otherUserId = conv.getUser1Id().equals(userId) ?
//                    conv.getUser2Id() : conv.getUser1Id();
//            UserEntity otherUser = userService.getUserById(otherUserId);
//            // 判断用户是否被删除
//          if (otherUser.getIsDelete().equals("1")){
//             // 把这个查询记录删除掉
//              conversations.remove(conv);
//              return dto;
//          }
//            dto.setOtherUser(otherUser);
//
//            // 获取最后一条消息
//            if (conv.getLastMessageId() != null) {
//                ChatMessagesEntity lastMsg = chatMessagesService.getById(conv.getLastMessageId());
//                dto.setLastMessage(lastMsg.getPostMessages());
//                dto.setLastMessageType(lastMsg.getMessagesType());
//                dto.setType(lastMsg.getType());
//                dto.setLastMessageTime(lastMsg.getTime());
//            }
//            // 判断用户是用户1还是用户2
//            if (conv.getUser1Id().equals(userId)) {
//                dto.setUnreadCount(conv.getUser1UnreadCount());
//            } else {
//                dto.setUnreadCount(conv.getUser2UnreadCount());
//            }
//            return dto;
//        }).sorted(Comparator.comparing((ConversationDto dto) -> {
//            ChatConversationEntity conv = conversations.stream()
//                    .filter(c -> c.getId().equals(dto.getConversationId()))
//                    .findFirst()
//                    .orElse(null);
//            if (conv != null) {
//                if (conv.getUser1Id().equals(userId)) {
//                    return conv.isUser1IsPinned() ? 0 : 1;
//                } else {
//                    return conv.isUser2IsPinned() ? 0 : 1;
//                }
//            }
//            return 1;
//        }).thenComparing(dto -> {
//            ChatConversationEntity conv = conversations.stream()
//                    .filter(c -> c.getId().equals(dto.getConversationId()))
//                    .findFirst()
//                    .orElse(null);
//            return conv != null ? conv.getUpdateTime() : null;
//        }, Comparator.reverseOrder())).toList();
//    }
    @Override
    public List<ConversationDto> getUserConversations(String userId) {
//        // 1. 查询用户参与的所有会话
//        List<ChatConversationEntity> conversations = lambdaQuery()
//                .and(q -> q.eq(ChatConversationEntity::getUser1Id, userId)
//                        .or()
//                        .eq(ChatConversationEntity::getUser2Id, userId))
//                .exists("SELECT 1 FROM chat_messages WHERE chat_messages.conversation_id  = chat_conversation.id")
//                .orderByDesc(ChatConversationEntity::getUpdateTime)
//                .list();
        // 1. 查询用户参与的所有会话（新增：排除已删除的会话）
        List<ChatConversationEntity> conversations = lambdaQuery()
                .and(q -> q.eq(ChatConversationEntity::getUser1Id,  userId)
                        .or().eq(ChatConversationEntity::getUser2Id, userId))
                // 核心新增条件：过滤当前用户已删除的会话
                .and(q -> q.eq(ChatConversationEntity::getUser1Id,  userId)
                        .ne(ChatConversationEntity::isUser1IsDeleted, 1) // 用户1未删除
                        .or()
                        .eq(ChatConversationEntity::getUser2Id, userId)
                        .ne(ChatConversationEntity::isUser2IsDeleted, 1)) // 用户2未删除
                .exists("SELECT 1 FROM chat_messages WHERE chat_messages.conversation_id  = chat_conversation.id")
                .orderByDesc(ChatConversationEntity::getUpdateTime)
                .list();
        if (conversations.isEmpty()) {
            return List.of();
        }

        // 筛除没有聊天记录的会话

        // 2. 获取所有相关“对方用户”的 ID
        List<String> otherUserIds = conversations.stream()
                .map(conv -> conv.getUser1Id().equals(userId) ? conv.getUser2Id() : conv.getUser1Id())
                .distinct()
                .collect(Collectors.toList());

        // 3. 批量获取用户信息（核心优化点）
        List<UserEntity> otherUsers = userService.listByIds(otherUserIds);

        // 4. 构建 Map 缓存，方便后续查找
        Map<String, UserEntity> userMap = otherUsers.stream()
                .collect(Collectors.toMap(UserEntity::getId, user -> user));

        // 5. 过滤掉对方用户已被删除的会话
        List<ChatConversationEntity> validConversations = conversations.stream()
                .filter(conv -> {
                    String otherUserId = conv.getUser1Id().equals(userId) ?
                            conv.getUser2Id() : conv.getUser1Id();
                    UserEntity otherUser = userMap.get(otherUserId);
                    return otherUser != null && 1 != otherUser.getIsDelete();
                })
                .toList();

        // 6. 转换为 DTO 并填充字段
        List<ConversationDto> dtoList = validConversations.stream()
                .map(conv -> {
                    ConversationDto dto = new ConversationDto();
                    dto.setConversationId(conv.getId());

                    String otherUserId = conv.getUser1Id().equals(userId) ?
                            conv.getUser2Id() : conv.getUser1Id();
                    UserEntity otherUser = userMap.get(otherUserId);
                    dto.setOtherUser(otherUser);

                    // 设置最后一条消息
                    if (conv.getLastMessageId() != null) {
                        ChatMessagesEntity lastMsg = chatMessagesService.getById(conv.getLastMessageId());
                        if (lastMsg != null) {
                            dto.setLastMessageType(lastMsg.getMessagesType());
                            if (lastMsg.getType().equals("1")) {
                                dto.setLastMessage("图片");
                            }else if (lastMsg.getType().equals("2")) {
                                dto.setLastMessage("视频");
                            }else {
                                dto.setLastMessage(lastMsg.getPostMessages());
                            }
                            dto.setType(lastMsg.getType());
                            dto.setLastMessageTime(lastMsg.getTime());
                            if (lastMsg.getMsgStatus().equals("3")) {
                                if (lastMsg.getFormUserId().equals(userId)) {
                                    dto.setLastMessage("你" + lastMsg.getPostMessages());
                                } else {
                                    dto.setLastMessage("对方" + lastMsg.getPostMessages());
                                }

                            }
                        }
                    }
//                    QueryWrapper<ChatMessagesEntity> queryWrapper = new QueryWrapper<>();
//                    queryWrapper.eq("conversation_id", conv.getId());
//                    queryWrapper.eq("to_user_id", userId).
//                            eq("msg_status", ChatMessageConstant.MESSAGE_STATUS_UNREAD).in("")
                    // 设置未读数
                    if (conv.getUser1Id().equals(userId)) {
                        dto.setUnreadCount(conv.getUser1UnreadCount());
                    } else {
                        dto.setUnreadCount(conv.getUser2UnreadCount());
                    }

                    return dto;
                })
                .toList();

        // 7. 排序逻辑保持不变
        return dtoList.stream()
                .sorted(Comparator.comparing((ConversationDto dto) -> {
                    ChatConversationEntity conv = conversations.stream()
                            .filter(c -> c.getId().equals(dto.getConversationId()))
                            .findFirst()
                            .orElse(null);
                    if (conv != null) {
                        if (conv.getUser1Id().equals(userId)) {
                            return conv.isUser1IsPinned() ? 0 : 1;
                        } else {
                            return conv.isUser2IsPinned() ? 0 : 1;
                        }
                    }
                    return 1;
                }).thenComparing(dto -> {
                    ChatConversationEntity conv = conversations.stream()
                            .filter(c -> c.getId().equals(dto.getConversationId()))
                            .findFirst()
                            .orElse(null);
                    return conv != null ? conv.getUpdateTime() : null;
                }, Comparator.reverseOrder()))
                .toList();
    }

    /**
     * 删除会话（逻辑删除）
     * <p>
     * 该方法用于标记删除指定的会话记录。删除操作为逻辑删除，即只更新删除标记而不真正删除数据。
     * 只有会话的参与者才能执行删除操作。
     *
     * @param userId         用户ID，执行删除操作的用户ID
     * @param conversationId 会话ID，需要被删除的会话记录ID
     * @return boolean 删除操作是否成功，成功返回true，失败返回false
     * @throws CampusException 当会话不存在或当前用户无权操作时抛出异常
     */
    @Transactional
    @Override
    public boolean deleteConversation(String userId, Long conversationId) {
        // 1. 校验会话是否存在且用户为会话参与者
        ChatConversationEntity conversation = lambdaQuery()
                .eq(ChatConversationEntity::getId, conversationId)
                .and(q -> q.eq(ChatConversationEntity::getUser1Id,  userId)
                        .or().eq(ChatConversationEntity::getUser2Id, userId))
                .one();
        if (conversation == null) {
            throw new CampusException("会话不存在或无权操作",201);
        }

        // 2. 根据用户角色（user1/user2）更新对应删除标记
        LambdaUpdateWrapper<ChatConversationEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ChatConversationEntity::getId,  conversationId);
        if (conversation.getUser1Id().equals(userId))  {
            updateWrapper.set(ChatConversationEntity::isUser1IsDeleted,  1); // 用户1标记删除
            updateWrapper.set(ChatConversationEntity::getUser1UnreadCount,  0); // 清空未读计数（可选，根据产品需求）
        } else {
            updateWrapper.set(ChatConversationEntity::isUser2IsDeleted,  1); // 用户2标记删除
            updateWrapper.set(ChatConversationEntity::getUser2UnreadCount,  0); // 清空未读计数（可选）
        }
        return update(updateWrapper);
    }

   @Override
   public List<ConversationDto> getUserConversationsByRedDot(String userId) {
        // 1. 查询用户参与的所有会话
        List<ChatConversationEntity> conversations = lambdaQuery()
                .and(q -> q.eq(ChatConversationEntity::getUser1Id, userId)
                        .or()
                        .eq(ChatConversationEntity::getUser2Id, userId))
                .exists("SELECT 1 FROM chat_messages WHERE chat_messages.conversation_id  = chat_conversation.id")
                .orderByDesc(ChatConversationEntity::getUpdateTime)
                .list();

        if (conversations.isEmpty()) {
            return List.of();
        }

        // 筛除没有聊天记录的会话

        // 2. 获取所有相关“对方用户”的 ID
        List<String> otherUserIds = conversations.stream()
                .map(conv -> conv.getUser1Id().equals(userId) ? conv.getUser2Id() : conv.getUser1Id())
                .distinct()
                .collect(Collectors.toList());

        // 3. 批量获取用户信息（核心优化点）
        List<UserEntity> otherUsers = userService.listByIds(otherUserIds);

        // 4. 构建 Map 缓存，方便后续查找
        Map<String, UserEntity> userMap = otherUsers.stream()
                .collect(Collectors.toMap(UserEntity::getId, user -> user));

        // 5. 过滤掉对方用户已被删除的会话
        List<ChatConversationEntity> validConversations = conversations.stream()
                .filter(conv -> {
                    String otherUserId = conv.getUser1Id().equals(userId) ?
                            conv.getUser2Id() : conv.getUser1Id();
                    UserEntity otherUser = userMap.get(otherUserId);
                    return otherUser != null && 1 != otherUser.getIsDelete();
                })
                .toList();

        // 6. 转换为 DTO 并填充字段
        List<ConversationDto> dtoList = validConversations.stream()
                .map(conv -> {
                    ConversationDto dto = new ConversationDto();
                    dto.setConversationId(conv.getId());
//
//                    String otherUserId = conv.getUser1Id().equals(userId) ?
//                            conv.getUser2Id() : conv.getUser1Id();
//                    UserEntity otherUser = userMap.get(otherUserId);
//                    dto.setOtherUser(otherUser);

//                    // 设置最后一条消息
//                    if (conv.getLastMessageId() != null) {
//                        ChatMessagesEntity lastMsg = chatMessagesService.getById(conv.getLastMessageId());
//                        if (lastMsg != null) {
//                            dto.setLastMessageType(lastMsg.getMessagesType());
//                            if (lastMsg.getType().equals("1")) {
//                                dto.setLastMessage("图片");
//                            }else if (lastMsg.getType().equals("2")) {
//                                dto.setLastMessage("视频");
//                            }else {
//                                dto.setLastMessage(lastMsg.getPostMessages());
//                            }
//                            dto.setType(lastMsg.getType());
//                            dto.setLastMessageTime(lastMsg.getTime());
//                            if (lastMsg.getMsgStatus().equals("3")) {
//                                if (lastMsg.getFormUserId().equals(userId)) {
//                                    dto.setLastMessage("你" + lastMsg.getPostMessages());
//                                } else {
//                                    dto.setLastMessage("对方" + lastMsg.getPostMessages());
//                                }
//
//                            }
//                        }
//                    }
                    // 设置未读数
                    if (conv.getUser1Id().equals(userId)) {
                        dto.setUnreadCount(conv.getUser1UnreadCount());
                    } else {
                        dto.setUnreadCount(conv.getUser2UnreadCount());
                    }

                    return dto;
                })
                .toList();

        // 7. 排序逻辑保持不变
        return dtoList;
    }

    /**
     * 置顶或取消置顶会话
     *
     * @param conversationId 会话ID
     * @param isPinned       是否置顶
     * @return 操作结果
     */
    @Override
    public boolean pinConversation(String conversationId, boolean isPinned, String userId) {
        log.info("conversationId:{},isPinned:{}", conversationId, isPinned);
        ChatConversationEntity conv = baseMapper.selectById(conversationId);
        if (conv.getUser1Id().equals(userId)) {
            conv.setUser1IsPinned(isPinned);
        } else {
            conv.setUser2IsPinned(isPinned);
        }
        int result = baseMapper.updateById(conv);
        return result > 0;
    }

    /**
     * @param conversationId
     * @param messageId
     * @return
     */
    @Override
    public boolean isLastMessage(String conversationId, String messageId) {
        ChatConversationEntity conv = baseMapper.selectById(conversationId);
        if (conv.getLastMessageId().equals(messageId)) {
            return true;
        }
        return false;
    }
    /**
     * @param userId
     * @param toUserId
     * @return
     */
    @Override
    public void checkConversationByTransfer(String userId, String toUserId) {
        log.info("userId:{},toUserId:{}", userId, toUserId);
        if (userId.equals(toUserId)) {
            throw new CampusException("不能与自己聊天", 201);
        }
        UserEntity user = userService.getUserById(userId);
        UserEntity toUser = userService.getUserById(toUserId);
        log.info("user:{},toUser:{}", user, toUser);
        if (user == null || toUser == null) {
            throw new CampusException("用户不存在", 201);
        }
        int compareResult = userId.compareTo(toUserId);
        String sortedUser1 = compareResult < 0 ? userId : toUserId;
        String sortedUser2 = compareResult < 0 ? toUserId : userId;

        ChatConversationEntity entity = baseMapper.selectOne(new LambdaQueryWrapper<ChatConversationEntity>().
                eq(ChatConversationEntity::getUser1Id, sortedUser1).
                eq(ChatConversationEntity::getUser2Id, sortedUser2));
        if (entity == null) {
            throw new CampusException("为保障资金安全，请双方完成首次对话后再进行转账", 201);
        }
        QueryWrapper<ChatMessagesEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("conversation_id", entity.getId());
        queryWrapper.eq("form_user_id",toUserId );
        queryWrapper.orderByDesc("time");
        queryWrapper.last("limit 1");
        ChatMessagesEntity message = chatMessagesService.getOne(queryWrapper);
        if (message == null) {
            throw new CampusException("为保障资金安全，请双方完成首次对话后再进行转账", 201);
        }
    }
    /**
     * @param conversationId
     */
    @Override
    public void updateRecallMessageId(String conversationId) {
        ChatConversationEntity conv = baseMapper.selectById(conversationId);
        if (!conv.getLastRecordId().isEmpty()) {
            conv.setLastMessageId(conv.getLastRecordId());
        }
        baseMapper.updateById(conv);

    }
}
